package com.xuan.webwork.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.xuan.webwork.entitys.Teacher;
import com.xuan.webwork.service.TeacherService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Controller
@RequestMapping("/teachers")
public class TeacherController {

    private final TeacherService teacherService;

    @Autowired
    public TeacherController(TeacherService teacherService) {
        this.teacherService = teacherService;
    }

    // 显示教师管理页面
    @GetMapping("/list")
    public String listTeachers(Model model) {
        List<Teacher> teachers = teacherService.getAllTeachers();
        model.addAttribute("teachers", teachers);
        return "teacher-list";
    }

    // 获取所有教师数据（Ajax API）
    @GetMapping("/api/all")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getAllTeachers() {
        Map<String, Object> response = new HashMap<>();
        try {
            List<Teacher> teachers = teacherService.getAllTeachers();
            response.put("code", 0);
            response.put("msg", "");
            response.put("count", teachers.size());
            response.put("data", teachers);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 1);
            response.put("msg", "获取教师数据失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    // 根据ID获取教师信息（Ajax API）
    @GetMapping("/api/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getTeacherById(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        try {
            Optional<Teacher> teacher = teacherService.getTeacherById(id);
            if (teacher.isPresent()) {
                response.put("code", 0);
                response.put("msg", "成功");
                response.put("data", teacher.get());
            } else {
                response.put("code", 1);
                response.put("msg", "教师不存在");
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 1);
            response.put("msg", "获取教师信息失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    // 新增教师（Ajax API）
    @PostMapping("/api/add")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> addTeacher(@RequestBody Teacher teacher) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 检查教师编号是否已存在
            if (teacherService.existsByTeacherId(teacher.getTeacherId())) {
                response.put("code", 1);
                response.put("msg", "教师编号已存在");
                return ResponseEntity.ok(response);
            }

            Teacher savedTeacher = teacherService.saveTeacher(teacher);
            response.put("code", 0);
            response.put("msg", "教师添加成功");
            response.put("data", savedTeacher);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 1);
            response.put("msg", "添加教师失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    // 更新教师信息（Ajax API）
    @PutMapping("/api/update/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> updateTeacher(@PathVariable Long id, @RequestBody Teacher teacher) {
        Map<String, Object> response = new HashMap<>();
        try {
            Optional<Teacher> existingTeacher = teacherService.getTeacherById(id);
            if (!existingTeacher.isPresent()) {
                response.put("code", 1);
                response.put("msg", "教师不存在");
                return ResponseEntity.ok(response);
            }

            // 检查教师编号是否被其他教师使用
            Optional<Teacher> teacherWithSameId = teacherService.getTeacherByTeacherId(teacher.getTeacherId());
            if (teacherWithSameId.isPresent() && !teacherWithSameId.get().getId().equals(id)) {
                response.put("code", 1);
                response.put("msg", "教师编号已被其他教师使用");
                return ResponseEntity.ok(response);
            }

            teacher.setId(id);
            Teacher updatedTeacher = teacherService.saveTeacher(teacher);
            response.put("code", 0);
            response.put("msg", "教师信息更新成功");
            response.put("data", updatedTeacher);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 1);
            response.put("msg", "更新教师信息失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    // 删除教师（Ajax API）
    @DeleteMapping("/api/delete/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> deleteTeacher(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        try {
            Optional<Teacher> teacher = teacherService.getTeacherById(id);
            if (!teacher.isPresent()) {
                response.put("code", 1);
                response.put("msg", "教师不存在");
                return ResponseEntity.ok(response);
            }

            teacherService.deleteTeacherById(id);
            response.put("code", 0);
            response.put("msg", "教师删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 1);
            response.put("msg", "删除教师失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    // 搜索教师（Ajax API）
    @GetMapping("/api/search")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> searchTeachers(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String department,
            @RequestParam(required = false) String title) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<Teacher> teachers = teacherService.findTeachersByConditions(name, department, title);
            response.put("code", 0);
            response.put("msg", "");
            response.put("count", teachers.size());
            response.put("data", teachers);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 1);
            response.put("msg", "搜索教师失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
}
